const { getApiUrl } = require('../../config/config')

Component({
  properties: {
    show: {
      type: Boolean,
      value: false
    }
  },
  data: {
    email: '',
    captcha: '',
    newPassword: '',
    checkPassword: '',
    isSendingCaptcha: false,
    captchaText: '获取验证码',
    captchaTimer: 0,
    showPassword: false,
    showCheckPassword: false,
    loading: false,
    errorMessage: '',
    successMessage: ''
  },
  methods: {
    // 处理输入变化
    handleInputChange(e) {
      const { field } = e.currentTarget.dataset
      this.setData({
        [field]: e.detail.value,
        errorMessage: ''
      })
    },
    
    // 发送验证码
    sendCaptcha() {
      const { email, isSendingCaptcha } = this.data
      
      // 防止重复发送
      if (isSendingCaptcha) return
      
      // 验证邮箱格式
      if (!email || !/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(email)) {
        this.setData({
          errorMessage: '请输入有效的邮箱地址'
        })
        return
      }
      
      this.setData({ 
        isSendingCaptcha: true,
        loading: true
      })
      
      wx.request({
        url: getApiUrl('/captcha'),
        method: 'POST',
        data: {
          email: email
        },
        success: (res) => {
          if (res.data.code === 200) {
            this.setData({
              successMessage: '验证码已发送，请查看邮箱',
              errorMessage: ''
            })
            this.startCaptchaTimer()
          } else {
            this.setData({
              errorMessage: res.data.message || '验证码发送失败'
            })
          }
        },
        fail: (error) => {
          console.error('Send captcha failed:', error)
          this.setData({
            errorMessage: '网络错误，请稍后再试'
          })
        },
        complete: () => {
          this.setData({ loading: false })
        }
      })
    },
    
    // 开始验证码倒计时
    startCaptchaTimer() {
      this.setData({
        captchaTimer: 60,
        captchaText: '60秒后重新获取'
      })
      
      const timer = setInterval(() => {
        const { captchaTimer } = this.data
        if (captchaTimer <= 1) {
          clearInterval(timer)
          this.setData({
            captchaTimer: 0,
            captchaText: '获取验证码',
            isSendingCaptcha: false
          })
        } else {
          this.setData({
            captchaTimer: captchaTimer - 1,
            captchaText: `${captchaTimer - 1}秒后重新获取`
          })
        }
      }, 1000)
    },
    
    // 切换密码可见性
    togglePasswordVisibility(e) {
      const field = e.currentTarget.dataset.field
      console.log('切换密码可见性', field, this.data[field])
      
      // 使用setTimeout确保状态更新后视图会刷新
      setTimeout(() => {
        this.setData({
          [field]: !this.data[field]
        })
      }, 0)
    },
    
    // 切换第一个密码可见性
    togglePassword() {
      console.log('切换新密码可见性', this.data.showPassword)
      this.setData({
        showPassword: !this.data.showPassword
      })
    },
    
    // 切换确认密码可见性
    toggleCheckPassword() {
      console.log('切换确认密码可见性', this.data.showCheckPassword)
      this.setData({
        showCheckPassword: !this.data.showCheckPassword
      })
    },
    
    // 重置密码
    resetPassword() {
      const { email, captcha, newPassword, checkPassword } = this.data
      
      // 表单验证
      if (!email) {
        this.setData({ errorMessage: '请输入邮箱' })
        return
      }
      if (!captcha) {
        this.setData({ errorMessage: '请输入验证码' })
        return
      }
      if (!newPassword) {
        this.setData({ errorMessage: '请输入新密码' })
        return
      }
      if (newPassword.length < 8) {
        this.setData({ errorMessage: '密码长度不能小于8位' })
        return
      }
      if (newPassword !== checkPassword) {
        this.setData({ errorMessage: '两次输入的密码不一致' })
        return
      }
      
      this.setData({ loading: true })
      
      wx.request({
        url: getApiUrl('/user/resetPassword'),
        method: 'POST',
        data: {
          email,
          captcha,
          newPassword,
          checkPassword
        },
        success: (res) => {
          if (res.data.code === 200) {
            this.setData({
              successMessage: '密码重置成功',
              errorMessage: '',
              email: '',
              captcha: '',
              newPassword: '',
              checkPassword: ''
            })
            
            // 通知父组件密码重置成功
            this.triggerEvent('success')
            
            // 3秒后关闭组件
            setTimeout(() => {
              this.triggerEvent('close')
            }, 3000)
          } else {
            this.setData({
              errorMessage: res.data.message || '密码重置失败'
            })
          }
        },
        fail: (error) => {
          console.error('Reset password failed:', error)
          this.setData({
            errorMessage: '网络错误，请稍后再试'
          })
        },
        complete: () => {
          this.setData({ loading: false })
        }
      })
    },
    
    // 关闭组件
    close() {
      this.triggerEvent('close')
    }
  }
}) 